﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;
using Model;
using Model.Enum;
using Components;

namespace UI.Lib
{
    public class UIValidation
    {
        private static string[] texts = new string[] { "字符串","整数", "大于零的整数", "大于或等于零的整数", "数字", "大于零的数字", 
            "大于或等于零的数字","日期类型。如(2010-08-09)", "日期时间类型。如(2010-08-09 12:43:52)", "时间类型。如(12:43:52)", 
            "手机格式","电话格式", "邮件格式","网址格式", "中文","身份证格式","编码类型，编码只能由数字、拼音组成"};

        public static string Validate(PsDataType tp, object o)
        {
            if (o == null) return "";

            bool _err = false;
            string _val = o.ToString();
            Regex r = null;

            switch (tp)
            {
                case PsDataType.Int: //整数
                case PsDataType.IntThanZero:
                case PsDataType.IntThanZeroOrEqualZero:
                    _err = !Validation.IsInt(o.ToString()) || _val.IndexOf('.') > -1;
                    if (tp == PsDataType.IntThanZero && !_err) _err = Validation.ToInt(_val) <= 0;
                    else if (tp == PsDataType.IntThanZeroOrEqualZero && !_err) _err = Validation.ToInt(_val) < 0;
                    break;
                case PsDataType.Num: //数字
                case PsDataType.NumThanZero:
                case PsDataType.NumThanZeroOrEqualZero:
                    _err = !Validation.IsFloat(_val);
                    if (tp == PsDataType.NumThanZero && !_err) _err = Validation.ToFloat(_val) <= 0;
                    else if (tp == PsDataType.NumThanZeroOrEqualZero && !_err) _err = Validation.ToFloat(_val) < 0;
                    break;
                case PsDataType.Date: break;
                case PsDataType.Datetime: break;
                case PsDataType.Time: break;
                case PsDataType.Phone:
                    r = new Regex(@"(\d{3,4}|\d{3,4}-)?\d{6,8}");
                    _err = !(r.IsMatch(_val));
                    break;
                case PsDataType.Tel: 
                    r = new Regex(@"(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^\([0-9]{3,4}\)[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)");
                    _err = !(r.IsMatch(_val));
                    break;
                case PsDataType.Mail:
                    r = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                    _err = !(r.IsMatch(_val));
                    break;
                case PsDataType.Url: break;
                case PsDataType.Cn: break;
                case PsDataType.CnId: break;
                case PsDataType.Code:
                    r = new Regex("[A-Za-z0-9]"); //编码字段只能由数字或者字符组成
                    _err = !(r.IsMatch(_val));
                    break;
            }

            if (!_err) return "";

            return "必须是" + texts[Convert.ToInt32(tp)];
        }

        public static string ValidateGrid(DataGridView dg, string[] notNullstr, string[] unqius)
        {
            return UIValidation.ValidateGrid(dg, notNullstr, unqius, null);
        }

        /// <summary>
        /// 验证GridView
        /// </summary>
        /// <param name="dg">GridView对象</param>
        /// <param name="notNullstr">不为空的字段集合</param>
        /// <param name="unqius">唯一键的字段集合</param>
        /// <param name="eqthans">大于零的字段集合</param>
        /// <returns></returns>
        public static string ValidateGrid(DataGridView dg, string[] notNullstr, string[] unqius, params VidationModel[] eqthans)
        {
            if (null == dg || 0 == dg.Rows.Count) return "";

            DataGridViewColumnCollection cc = dg.Columns;
            Hashtable hsVal = null; //键=>唯一键的相关列组成的字符串
            StringBuilder key = null;
            string v = "";
            string msg = "";

            foreach (DataGridViewRow dr in dg.Rows)
            {
                if (null != notNullstr) //判断空
                {
                    foreach (string c in notNullstr)
                    {
                        if (!cc.Contains(c)) continue;

                        if (null == dr.Cells[c].Value || "" == dr.Cells[c].Value.ToString())
                        {
                            if (dr.Cells[c].Visible == false) continue;
                            dr.Cells[c].Selected = true;
                            return "第（" + (dr.Index + 1) + "）行[" + cc[c].HeaderText + "]不能为空！";
                        }
                    }
                }

                if (null != unqius) //验证唯一性
                {
                    if (hsVal == null)
                    {
                        hsVal = new Hashtable();
                    }

                    key = new StringBuilder();
                    foreach (string c in unqius)
                    {
                        if (!cc.Contains(c)) continue;
                        v = (null == dr.Cells[c].Value) ? "" : dr.Cells[c].Value.ToString();

                        key.Append(v + "_");
                    }

                    if (hsVal.ContainsKey(key.ToString()))
                    {
                        return string.Format("第（{0}）行数据和第（{1}）行数据重复！", Convert.ToInt32(hsVal[key.ToString()]) + 1, dr.Index + 1);
                    }

                    hsVal[key.ToString()] = dr.Index;
                }

                if (null != eqthans) //判断字段类型
                {
                    foreach (VidationModel c in eqthans)
                    {
                        if (!cc.Contains(c.Name)) continue;
                        v = (null == dr.Cells[c.Name].Value) ? "" : dr.Cells[c.Name].Value.ToString();

                        msg = UIValidation.Validate(c.Type, v);
                        if (!string.IsNullOrEmpty(msg))
                        {
                            if (dr.Cells[c.Name].Visible == false) continue;
                            dr.Cells[c.Name].Selected = true;
                            return string.Format("第（{0}）行（{1}）{2}！", dr.Index + 1, cc[c.Name].HeaderText, msg);
                        }
                    }
                }
            }

            return "";
        }
    }
}
